﻿using Castle.Core.Configuration;
using FreeRedis.Internal;
using FreeSql;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace InfrastructureBase.Data
{
    public static class IFreeSqlExtesions
    {

        static IdleBus<IFreeSql> idleBus = new IdleBus<IFreeSql>(TimeSpan.FromMinutes(10));


        /// <summary>
        /// 支持数据库多库
        /// </summary>
        /// <param name="services"></param>
        /// <param name="sectionConfigStr">配置文件</param>
        /// <exception cref="ArgumentException"></exception>
        public static void AddFreeSqlMultService(this IServiceCollection services, string sectionConfigStr)
        {
            IFreeSqlConfig freeSqlConfig = AppSettingConfig.BindSection<IFreeSqlConfig>(sectionConfigStr);
            if (freeSqlConfig == null && string.IsNullOrEmpty(sectionConfigStr))
                throw new ArgumentException("数据库配置文件异常");

            if (freeSqlConfig.DBConfigs != null && freeSqlConfig.DBConfigs.Count > 0)
            {
                freeSqlConfig.DBConfigs?.ForEach(db =>
                {
                    idleBus.Register(db.ConnId, () => new FreeSqlBuilder().UseConnectionString((DataType)db.DataType, db.ConnectionString).Build());
                });
            }
            services.AddSingleton(idleBus);
        }

    }
}
